package com.yztstudy.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yztstudy.Mapper.CartMapper;
import com.yztstudy.Service.CartService;
import com.yztstudy.clients.ProductFeignClient;
import com.yztstudy.entity.Cart;
import com.yztstudy.entity.Product;
import com.yztstudy.param.CartListParam;
import com.yztstudy.param.CartSaveParam;
import com.yztstudy.param.ProductCollectParam;
import com.yztstudy.param.ProductIdParam;
import com.yztstudy.utils.R;
import com.yztstudy.vo.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Resource
    private ProductFeignClient productFeignClient;

    /**
     * TODO 添加购物车
     * @param cartSaveParam 前端传过来的参数
     * @return
     */
    @Transactional
    @Override
    public R save(CartSaveParam cartSaveParam) {

        // TODO 1.查询商品数据
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cartSaveParam.getProductId());
        Product product = productFeignClient.cartDetail(productIdParam);

        // TODO 2.检查库存
        if (product == null)
        {
            log.info("CartServiceImpl.save业务结束, 结果:{}", "商品已经被删除,无法添加到购物车!");
            return R.fail("商品已经被删除,无法添加到购物车!");
        }
        if (product.getProductNum() == 0)
        {
            log.info("CartServiceImpl.save业务结束, 结果:{}", "库存为0,无法购买!");
            R ok = R.ok("库存为0,无法购买!");
            ok.setCode("003");
            return ok;
        }

        // TODO 3.查询购物车是否存在
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", cartSaveParam.getUserId());
        wrapper.eq("product_id", cartSaveParam.getProductId());
        Cart cart = cartMapper.selectOne(wrapper); // 从数据库中查询
        if (cart != null) // 不为null，购物车存在
        {
            cart.setNum(cart.getNum() + 1);
            cartMapper.updateById(cart); // 更新数量
            log.info("CartServiceImpl.save业务结束, 结果:{}", "购物车存在该商品,数量+1!");
            R ok = R.ok("购物车存在该商品,数量+1!");
            ok.setCode("002");
            return ok;
        }

        // TODO 4.如果不存在，就添加
        cart = new Cart();
        cart.setNum(1);
        cart.setUserId(cartSaveParam.getUserId());
        cart.setProductId(cartSaveParam.getProductId());
        cartMapper.insert(cart);

        CartVo cartVo = new CartVo(product, cart); // 封装返回结果
        log.info("CartServiceImpl.save业务结束, 结果:{}", "购物车中的商品新增成功!");
        return R.ok("购物车中的商品新增成功!", cartVo);
    }


    /**
     * TODO 查看购物车
     * @param cartListParam 前端发过来的用户ID
     * @return
     */
    @Override
    public R list(CartListParam cartListParam) {

        // TODO 1.根据用户ID查询购物车数据
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", cartListParam.getUserId());
        List<Cart> carts = cartMapper.selectList(wrapper);

        // TODO 2.查看购物车里面是否有商品
        if (carts == null || carts.size() == 0)
        {
            carts = new ArrayList<>();
            log.info("CartServiceImpl.list业务结束, 结果:{}", "购物车空空如也!");
            return R.ok("购物车空空如也!", carts);
        }

        // TODO 3.转换为List<Integer>数组
        List<Integer> productIds = new ArrayList<>();
        for (Cart cart : carts)
        {
            productIds.add(cart.getProductId());
        }

        // TODO 4.远程调用
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(productIds);
        List<Product> products = productFeignClient.cartList(productCollectParam);

        // TODO 5.把结果封装为Map集合
        Map<Integer, Product> productMap = products.stream().collect(Collectors.toMap(Product::getProductId, v -> v));
        List<CartVo> cartVos = new ArrayList<>();
        for (Cart cart : carts)
        {
            CartVo cartVo = new CartVo(productMap.get(cart.getProductId()), cart);
            cartVos.add(cartVo);
        }

        log.info("CartServiceImpl.list业务结束, 结果:{}", "数据库查询成功!");
        return R.ok("数据库查询成功!", cartVos);
    }


    /**
     * TODO 更新购物车中的数据
     * @param cart 购物车
     * @return
     */
    @Transactional
    @Override
    public R update(Cart cart) {

        // TODO 1.查询商品的数据
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cart.getProductId());
        Product product = productFeignClient.cartDetail(productIdParam);

        // TODO 2.判断库存
        if (product.getProductNum() < cart.getNum())
        {
            log.info("CartServiceImpl.update业务结束, 结果:{}", "修改失败,库存不足!");
            return R.fail("修改失败,库存不足!");
        }

        // TODO 3.库存够就修改库存
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", cart.getUserId());
        wrapper.eq("product_id", cart.getProductId());
        Cart newCart = cartMapper.selectOne(wrapper);
        newCart.setNum(cart.getNum());

        cartMapper.updateById(newCart);
        log.info("CartServiceImpl.update业务结束, 结果:{}", "修改购物车中商品的数量成功!");
        return R.ok("修改购物车中商品的数量成功!");
    }


    /**
     * TODO 删除购物车中的数据
     * @param cart 购物车
     * @return
     */
    @Transactional
    @Override
    public R remove(Cart cart) {

        // TODO 1.构造删除条件
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", cart.getUserId());
        wrapper.eq("product_id", cart.getProductId());

        // TODO 2.删除
        cartMapper.delete(wrapper);
        log.info("CartServiceImpl.remove业务结束, 结果:{}", "删除购物车中商品成功!");
        return R.ok("删除购物车中商品成功!");
    }


    /**
     * TODO 清空对应id的购物车
     * @param cartIds 购物车id集合
     */
    @Transactional
    @Override
    public void clearIds(List<Integer> cartIds) {
        // TODO 1.直接批量删除
        cartMapper.deleteBatchIds(cartIds);
        log.info("CartServiceImpl.clearIds业务结束, 结果:{}", "删除多个购物车数据成功!");
    }


    /**
     * TODO 检查购物车中是否有要删除的商品
     * @param productId 商品的Id
     * @return
     */
    @Override
    public R check(Integer productId) {

        // TODO 1.构造查询条件
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId);
        Long count = cartMapper.selectCount(wrapper);

        // TODO 2.判断
        if (count == 0L)
        {
            return R.ok("购物车中不存在要删除的商品!");
        }
        else {
            return R.fail("购物车中存在要删除的商品!");
        }
    }
}
